package com.card.admin.servelt;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.card.admin.pojo.Admin;
import com.card.admin.pojo.AdminManager;
import com.card.user.User;
import com.xiaoao.net.utils.StringUtil;

public class LoginServletPhone extends HttpServlet {
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		//1,接收请求参数
		//2.调用业务逻辑类，处理登录请求
		//,如果登录成功，将User对象存入Session，并重定向login.jsp
		//,登录失败，转重定向login.jsp;
		res.setContentType("text/plain;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		HttpSession session = req.getSession();
		session.setAttribute("admin", null);
		if(session.getAttribute("admin") == null) {
			String userName = req.getParameter("username");
			String password = req.getParameter("pwd");
			if(StringUtil.NullOrEmpty(userName) || StringUtil.NullOrEmpty(password)) {
				System.out.println("login*********--error");
				req.getRequestDispatcher("/m_info.jsp?info=4").forward(req, res);
				return;
			}
			System.out.println("login-----success---"+userName+"-"+password);
			
			Admin admin = AdminManager.getInstance().getAdmin(userName);
			if(admin != null && StringUtil.equals(password, admin.getPassword())
					&&admin.isFree()) {
				System.out.println("login-----success---"+userName+"-"+password);
				session.setAttribute("admin", admin);
				session.setMaxInactiveInterval(3000);
				
				sendPage(req,res);
			}else{
				System.out.println("login*********--error");
				req.getRequestDispatcher("/m_info.jsp?info=4").forward(req, res);
			}
		}else{
			sendPage(req,res);
		}
	}
	private void sendPage(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		Admin admin = (Admin)req.getSession().getAttribute("admin");
		int group = admin.getGroup();
		if(group == 1) {
			req.getRequestDispatcher("/m_agent.jsp").forward(req, res);
		}else{
			req.getRequestDispatcher("/m_agent_info.jsp").forward(req, res);
		}
	}
}
